package com.a.learning_keep.myapp

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.a.learning_keep.databinding.ActivityMainBinding
import android.os.Handler
import android.util.SparseArray
import android.view.KeyEvent
import android.widget.Toast
import androidx.core.util.forEach
import androidx.fragment.app.Fragment
import com.a.learning_keep.R
import com.a.learning_keep.frag.*
import com.a.learning_keep.base.token

class MainActivity : AppCompatActivity() {

    lateinit var bd: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bd = ActivityMainBinding.inflate(layoutInflater)
        setContentView(bd.root)
        initView()
    }

    var sta = false
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (event!!.action == KeyEvent.ACTION_DOWN) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if (!sta) {
                    Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show()
                    sta = true
                } else {
                    finishAffinity()
                    token = ""
                }


                Handler().postDelayed({
                    sta = false
                }, 1500)

            }
        }

        return true
    }

    var spa = SparseArray<Fragment>().apply {
        put(R.id.navigation_home, Fragment1Home())
        put(R.id.navigation_dress_up, Fragment2DressUp())
        put(R.id.navigation_shop, Fragment3Shop())
        put(R.id.navigation_game, Fragment4Game())
        put(R.id.navigation_ranking, Fragment5Ranking())
    }

    var current = spa[R.id.navigation_home]

    private fun initView() {

        supportFragmentManager.beginTransaction().apply {
            spa.forEach { key, value ->
                add(R.id.main, value)
                if (value != current)
                    hide(value)
            }
        }.commit()

        bd.nav.setOnNavigationItemSelectedListener {
            val fragment = spa[it.itemId]
            if (fragment != current) {
                supportFragmentManager.beginTransaction().show(fragment).hide(current).commit()
                current = fragment
            }
            true
        }

    }



}